<template>
  <div class="main">
    <div class="part">
      <div class="p-title">
        <div class="title">用户管理</div>
        <div class="search-warp">
          <el-input
            v-model="searchContent"
            placeholder="请输入用户名进行搜索"
            @change="searchDrugs"
          >
            <template #append>
              <el-button :icon="Search" />
            </template>
          </el-input>
        </div>
      </div>
      <div class="p-cont">
        <div class="opr">
          <div class="opr-left">
            <el-button type="primary" @click="showCreateUserDialog"
              >新建用户</el-button
            >
            <!-- <el-button plain>批量导入</el-button>
            <el-button link>
              <IconifyIconOnline
                icon="material-symbols:download"
                width="24px"
                height="24px"
              />下载导入模板</el-button
            > -->
          </div>
          <!-- <div class="opr-right">
            <el-input
              v-model="searchContent"
              placeholder="Please input"
              @change="searchDrugs"
            >
              <template #append>
                <el-button :icon="Search" />
              </template>
            </el-input>
          </div> -->
        </div>
        <div class="table-wrap">
          <el-table :data="userList" style="width: 100%" stripe>
            <el-table-column prop="name" label="姓名" />
            <el-table-column prop="loginName" label="用户名" />
            <el-table-column label="负责区域">
              <template #default="scope">
                <el-row
                  v-for="(areaObj, index) in scope.row.areaRanges"
                  :key="index"
                  >{{ formatDist(areaObj) }}</el-row
                >
              </template>
            </el-table-column>

            <el-table-column label="状态">
              <template #default="scope">
                {{ Number(scope.row.isDisabled) === 0 ? "正常" : "禁用" }}
              </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="editUser(scope.row)"
                  >编辑</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="del-btn">
          <div class="del-right">
            <myPagination
              :total="listNum || 0"
              @currentChange="currentChange"
              ref="myPaginationRef"
            />
          </div>
        </div>
        <div class="page">
          <div class="page-left">共{{ listNum }}条数据</div>
        </div>
      </div>

      <el-dialog
        v-model="dialogVisible"
        title="添加/编辑用户"
        :close-on-click-modal="false"
      >
        <div class="dialog-adddrug">
          <el-form
            :model="userForm"
            label-width="120px"
            ref="ruleFormRef"
            :rules="rules"
          >
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userForm.name" />
            </el-form-item>
            <el-form-item label="用户名" prop="loginName">
              <el-input v-model="userForm.loginName" />
            </el-form-item>
            <el-form-item
              label="密码"
              prop="password"
              :rules="[
                {
                  required: true,
                  message: '密码不能为空',
                  trigger: 'blur'
                },
                {
                  validator: validatePass,
                  trigger: 'blur'
                }
              ]"
              v-if="editType === 'new'"
            >
              <el-input
                v-model="userForm.password"
                type="password"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item
              label="确认密码"
              prop="rePassword"
              :rules="[
                {
                  required: true,
                  message: '确认密码不能为空',
                  trigger: 'blur'
                },
                {
                  validator: validatePass2,
                  trigger: 'blur'
                }
              ]"
              v-if="editType === 'new'"
            >
              <el-input
                v-model="userForm.rePassword"
                type="password"
                autocomplete="off"
              />
            </el-form-item>

            <el-form-item prop="mySelectedArea" label="管理区域">
              <el-row>
                <el-cascader
                  v-model="userForm.mySelectedArea"
                  :options="areaOptions"
                  @change="areaChange"
                  :props="cascaderProps"
                />
              </el-row>
            </el-form-item>
            <el-form-item prop="signsList" label="短信签名">
              <el-select
                v-model="userForm.signsList"
                placeholder="请选择短信签名"
                size="large"
                multiple
              >
                <el-option
                  v-for="item in globalSignList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="smsMargin" label="短信余量">
              <el-input v-model="userForm.smsMargin" autocomplete="off" />
            </el-form-item>

            <el-form-item label="状态" prop="isDisabled">
              <el-switch
                v-model="userForm.isDisabled"
                active-text="正常"
                inactive-text="禁用"
                :active-value="0"
                :inactive-value="1"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitUser">提交</el-button>
              <el-button @click="resetSubmit" v-if="editType === 'new'"
                >重置表单</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onBeforeMount, ref, reactive } from "vue";
import { getCommonRegions } from "../../api/user";
import { getUsersApi, createUsers, getUserConfiguration } from "@/api/system";
import { getSmsSignList } from "@/api/publicity";
import myPagination from "@/components/myPagination.vue";
import { useUserStoreHook } from "@/store/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";
import myProCityArea from "@/components/myProCityArea.vue";
import Close from "@iconify-icons/ep/Close";
import { number } from "echarts";
import { getUserRegions } from "@/api/user";
import { Search } from "@element-plus/icons-vue";
const userStore = useUserStoreHook();
const ruleFormRef = ref();
const listNum = ref(0);
const myPaginationRef = ref();
const userList = ref([]);
const dialogVisible = ref(false);
const editType = ref<"new" | "edit">("new");
const searchContent = ref();

const areaOptions = ref([]);
const originArea = ref([]);
// 当前登录人配置

// 全局签名列表
const globalSignList = ref([]);
const cascaderProps = {
  checkStrictly: true,
  multiple: true
};

const userForm = ref({
  sysUserId: "",
  name: "",
  loginName: "",
  password: "",
  rePassword: "",
  isDisabled: 0,
  mySelectedArea: [],
  areaRanges: [
    {
      type: 2,
      provinceId: "",
      cityId: "",
      areaId: ""
    }
  ],
  signsList: [],
  smsMargin: ""
});

function searchDrugs() {
  myPaginationRef.value.currentPage = 1;
  getUsers();
}
function validatePass(rule: any, value: any, callback: any) {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    if (userForm.value.rePassword !== "") {
      if (!ruleFormRef.value) {
        return;
      }
      ruleFormRef.value.validateField("rePassword", () => null);
    }
    callback();
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请在此输入密码"));
  } else if (value !== userForm.value.password) {
    callback(new Error("两次密码不匹配"));
  } else {
    callback();
  }
};

const rules = reactive({
  name: [
    {
      required: true,
      message: "姓名不能为空,且长度为2-30个字符",
      trigger: "blur",
      min: 2,
      max: 30
    }
  ],
  loginName: [
    {
      required: true,
      message: "用户名不能为空,且长度为2-50个字符",
      trigger: "blur",
      min: 2,
      max: 50
    }
  ],

  mySelectedArea: [
    { required: true, message: "管理区域不能为空", trigger: "blur" }
  ],
  signsList: [{ required: true, message: "短信签名不能为空", trigger: "blur" }],
  smsMargin: [{ required: true, message: "短信余量不能为空", trigger: "blur" }],
  isDisabled: [{ required: true, message: "管理区域不能为空", trigger: "blur" }]
});

function currentChange() {
  getUsers();
}
async function getUsers() {
  const queryObj = {
    skip:
      (myPaginationRef.value.currentPage - 1) *
      myPaginationRef.value.curPageSize,
    limit: myPaginationRef.value.curPageSize
  } as any;
  if (searchContent.value) {
    queryObj.loginName = searchContent.value;
  }
  const listRes = await getUsersApi(queryObj);
  userList.value = listRes.list;
  if (myPaginationRef.value.currentPage === 1) {
    listNum.value = listRes.total;
  }
}

function areaChange(valueList) {
  let selectedPro = "";
  let selectedCity = "";
  if (valueList.length > 0) {
    // 如果用户选择了区县，则需要其他市的选项取消掉，如果用户选择了市，则需要把其他省的选项取消掉
    let hasLen3 = false;
    let hasLen2 = false;
    let hasLen1 = false;
    valueList.forEach(itemArr => {
      if (itemArr.length === 3) {
        hasLen3 = true;
      } else if (itemArr.length === 2) {
        hasLen2 = true;
      } else if (itemArr.length === 1) {
        hasLen1 = true;
      }
    });

    if (hasLen3) {
      valueList = valueList.filter(itemArr => {
        return itemArr.length === 3;
      });
      if (hasLen1 || hasLen2) {
        ElMessage({
          message: "只能添加同地区同级区域的数据",
          type: "warning"
        });
      }
    }
    if (!hasLen3 && hasLen2) {
      valueList = valueList.filter(itemArr => {
        return itemArr.length === 2;
      });
      if (hasLen1) {
        ElMessage({
          message: "只能添加同地区同级区域的数据",
          type: "warning"
        });
      }
    }

    valueList.forEach(itemArr => {
      // 选择了市采用锁定省
      if (itemArr[1]) {
        selectedPro = itemArr[0];
      }

      // 选择了区县的话，才用锁定市
      if (itemArr[2]) {
        selectedCity = itemArr[1];
      }
    });
    // console.log("valueList2:", valueList);
    userForm.value.mySelectedArea = valueList;

    areaOptions.value = originArea.value.map(pro => {
      return {
        value: pro.id,
        label: pro.name,
        disabled: selectedPro && pro.id !== selectedPro ? true : false,
        children: pro.city.map(city => {
          return {
            value: city.id,
            label: city.name,
            disabled: selectedCity && city.id !== selectedCity ? true : false,
            children: city.area.map(area => {
              return {
                value: area.id,
                label: area.name
              };
            })
          };
        })
      };
    });
  } else {
    areaOptions.value = originArea.value.map(pro => {
      return {
        value: pro.id,
        label: pro.name,
        children: pro.city.map(city => {
          return {
            value: city.id,
            label: city.name,
            children: city.area.map(area => {
              return {
                value: area.id,
                label: area.name
              };
            })
          };
        })
      };
    });
  }
}

function resetUserForm() {
  userForm.value = {
    sysUserId: "",
    name: "",
    loginName: "",
    password: "",
    rePassword: "",

    mySelectedArea: [],
    isDisabled: 0, //是否禁用,0=正常,1=禁用
    areaRanges: [
      //负责区域
    ],
    signsList: [],
    smsMargin: ""
  };
}

function showCreateUserDialog() {
  dialogVisible.value = true;
  editType.value = "new";
  resetUserForm();
}
async function editUser(uData) {
  // console.log("editUser uData:", uData);
  dialogVisible.value = true;
  editType.value = "edit";
  // 获取用户配置
  const userConfig = await getUserConfiguration(uData.sysUserId);

  userForm.value = {
    ...uData,
    mySelectedArea: uData.areaRanges.map(item => {
      const tempArr = [];
      if (item.provinceId) {
        tempArr.push(item.provinceId);
      }
      if (item.cityId) {
        tempArr.push(item.cityId);
      }
      if (item.areaId) {
        tempArr.push(item.areaId);
      }
      return tempArr;
    }),
    signsList: userConfig ? userConfig.signs.split(",") : [],
    smsMargin: userConfig ? userConfig.smsMargin : ""
  };

  let hasLen3 = false;
  let hasLen2 = false;
  let hasLen1 = false;
  userForm.value.mySelectedArea.forEach(itemArr => {
    if (itemArr.length === 3) {
      hasLen3 = true;
    } else if (itemArr.length === 2) {
      hasLen2 = true;
    } else if (itemArr.length === 1) {
      hasLen1 = true;
    }
  });
  if (hasLen3) {
    userForm.value.mySelectedArea = userForm.value.mySelectedArea.filter(
      itemArr => {
        return itemArr.length === 3;
      }
    );
  }
  if (!hasLen3 && hasLen2) {
    userForm.value.mySelectedArea = userForm.value.mySelectedArea.filter(
      itemArr => {
        return itemArr.length === 2;
      }
    );
  }
  let selectedPro = "";
  let selectedCity = "";
  userForm.value.mySelectedArea.forEach(itemArr => {
    // 选择了市采用锁定省
    if (itemArr[1]) {
      selectedPro = itemArr[0];
    }

    // 选择了区县的话，才用锁定市
    if (itemArr[2]) {
      selectedCity = itemArr[1];
    }
  });
  areaOptions.value = originArea.value.map(pro => {
    return {
      value: pro.id,
      label: pro.name,
      disabled: selectedPro && pro.id !== selectedPro ? true : false,
      children: pro.city.map(city => {
        return {
          value: city.id,
          label: city.name,
          disabled: selectedCity && city.id !== selectedCity ? true : false,
          children: city.area.map(area => {
            return {
              value: area.id,
              label: area.name
            };
          })
        };
      })
    };
  });
}

function resetArea() {
  areaOptions.value = originArea.value.map(pro => {
    return {
      value: pro.id,
      label: pro.name,
      children: pro.city.map(city => {
        return {
          value: city.id,
          label: city.name,
          children: city.area.map(area => {
            return {
              value: area.id,
              label: area.name
            };
          })
        };
      })
    };
  });
}

function submitUser() {
  if (ruleFormRef.value) {
    ruleFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        const tempForm = Object.assign({}, userForm.value, { signs: "" });
        // 全国

        tempForm.areaRanges = userForm.value.mySelectedArea.map(item => {
          return {
            type: item.length + 1,
            provinceId: item[0] || "",
            cityId: item[1] || "",
            areaId: item[2] || ""
          };
        });

        // 删除自己添加的字段
        delete tempForm.rePassword;
        delete tempForm.mySelectedArea;
        delete tempForm.signsList;
        const tip = editType.value === "new" ? "新增" : "更新";

        tempForm.signs = userForm.value.signsList.join(",");
        if (editType.value === "new") {
          delete tempForm.sysUserId;
        }
        console.log("tempForm:", tempForm);
        try {
          const res = await createUsers({
            userId: userStore.userInfo.user,
            data: JSON.stringify(tempForm)
          });
          console.log("res:", res);
          if (!res || res.code === 0) {
            ElMessage({
              message: tip + "成功",
              type: "success"
            });
            resetUserForm();
          }
          resetArea();
          dialogVisible.value = false;
          getUsers();
          searchContent.value = tempForm.loginName;

          // 设置用户能够查看的数据范围
          const userRegionsRes = await getUserRegions(userStore.userInfo.user);
          userStore.SET_USERREGIONS(userRegionsRes);
        } catch (error) {
          ElMessage({
            message: tip + "失败," + JSON.stringify(error),
            type: "error"
          });
        }
      } else {
        console.log("error submit!", fields);
      }
    });
  }
}

function resetSubmit() {
  resetUserForm();
  // dialogVisible.value = false;
}

function formatDist(areaObj) {
  let temp = areaObj.provinceName;
  if (areaObj.cityName) {
    temp += "-" + areaObj.cityName;
  }
  if (areaObj.areaName) {
    temp += "-" + areaObj.areaName;
  }
  return temp;
}

onBeforeMount(async () => {
  const regionRes = await getCommonRegions();
  originArea.value = regionRes;
  globalSignList.value = await getSmsSignList();

  resetArea();
});

onMounted(async () => {
  // await getUsers();
});
</script>
<style scoped lang="scss">
::v-deep(.el-backtop) {
  display: none !important;
}

.main {
  .part {
    .p-title {
      justify-content: space-between;
    }
  }
}

.opr {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .opr-right {
    width: 300px;
  }
}

.table-wrap {
  margin-top: 20px;
}

.del-btn {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.page {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .page-left {
    color: #bbb;
  }
}

.dialog-adddrug {
  width: 400px;

  .dist-row {
    display: flex;
    align-items: center;

    .dist-btn {
      margin: 0px 10px 10px 0px;
    }
  }
}

.el-select {
  width: 100%;
}

.el-row {
  width: 100%;
}
</style>
